/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Common.h"

void AppendPackGUID(ByteBuffer& _Buffer, std::uint64_t _Guid)
{
    std::uint8_t _PackGUID[8 + 1];
    _PackGUID[0] = 0;
    size_t _Size = 1;
    for (std::uint8_t _I = 0; _Guid != 0; ++_I)
    {
        if (_Guid & 0xFF)
        {
            _PackGUID[0] |= std::uint8_t(1 << _I);
            _PackGUID[_Size] = std::uint8_t(_Guid & 0xFF);
            ++_Size;
        }
        _Guid >>= 8;
    }
    _Buffer.Append(_PackGUID, _Size);
}

std::uint64_t ReadPackGUID(ByteBuffer& _Buffer)
{
    std::uint64_t _Guid = 0;
    std::uint8_t _Guidmark = 0;
    _Buffer >> _Guidmark;

    for (int _I = 0; _I < 8; ++_I)
    {
        if (_Guidmark & (std::uint8_t(1) << _I))
        {
            std::uint8_t _Bit;
            _Buffer >> _Bit;
            _Guid |= (std::uint64_t(_Bit) << (_I * 8));
        }
    }
    return _Guid;
}